import React, { useState } from 'react';
import { Card, Button, message, Progress, Modal } from 'antd';
import AddPhoto from './components/AddPhoto';
import Layout from './components/Layout';
import type { UploadFile } from 'antd/es/upload/interface';
import styles from './index.module.less';

interface ImageInfo {
  fileList: UploadFile[];
  hasImage: boolean;
}

interface LayoutInfo {
  selectedLayout: string;
  hasLayout: boolean;
}

interface DownloadItem {
  url: string;
  fileName?: string;
}

const UploadPage: React.FC = () => {
  const [imageInfo, setImageInfo] = useState<ImageInfo>({
    fileList: [],
    hasImage: false
  });
  const [layoutInfo, setLayoutInfo] = useState<LayoutInfo>({
    selectedLayout: '',
    hasLayout: false
  });
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0);

  const handleImageSelect = (info: ImageInfo) => {
    setImageInfo(info);
    if (!info.hasImage) {
      setLayoutInfo({
        selectedLayout: '',
        hasLayout: false
      });
    }
  };

  const handleLayoutSelect = (info: LayoutInfo) => {
    setLayoutInfo(info);
  };

  const batchDownload = async (files: DownloadItem[]) => {
    try {
      for (const file of files) {
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = file.url;
        link.download = file.fileName || '下载文件';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      message.success(`${files.length} 个文件开始下载`);
    } catch (error) {
      message.error('下载失败');
      console.error('下载错误:', error);
    }
  };

  const simulateProgress = () => {
    let currentProgress = 0;
    const interval = setInterval(() => {
      currentProgress += Math.random() * 10;
      if (currentProgress > 100) {
        currentProgress = 100;
        clearInterval(interval);
        setLoading(false);
        setProgress(0);
        // 模拟下载文件
        const files = [
          { url: 'url1', fileName: 'file1.pdf' },
          { url: 'url2', fileName: 'file2.pdf' }
        ];
        batchDownload(files);
      }
      setProgress(Math.min(currentProgress, 100));
    }, 500);
  };

  const handleConfirm = () => {
    setLoading(true);
    simulateProgress();
  };

  return (
    <div className={styles.upload}>
      <div className={styles.uploadHeader}>
        <h1>网页布局生成器</h1>
        <h3>上传您的设计稿，选择合适的布局结构，快速生成响应式页面</h3>
      </div>
      <div className={styles.uploadContent}>
        <Card className={styles.card}>
          <AddPhoto onImageSelect={handleImageSelect} />
        </Card>
        <Card className={styles.card}>
          <Layout 
            onLayoutSelect={handleLayoutSelect} 
            disabled={!imageInfo.hasImage}
          />
        </Card>
      </div>
      <div className={styles.uploadFooter}>
        <Button 
          type="primary" 
          size="large"
          onClick={handleConfirm}
          disabled={!imageInfo.hasImage || !layoutInfo.hasLayout}
          style={{ 
            width: '200px',
            height: '40px',
            fontSize: '16px'
          }}
        >
          确认
        </Button>
      </div>

      <Modal
        title="正在生成代码"
        open={loading}
        footer={null}
        closable={false}
        maskClosable={false}
        centered
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <Progress 
            type="circle" 
            percent={Math.round(progress)} 
            format={percent => `${percent}%`}
            width={80}
          />
          <div style={{ marginTop: 16, color: '#666' }}>
            {progress < 30 && '正在分析设计稿...'}
            {progress >= 30 && progress < 60 && '正在生成代码...'}
            {progress >= 60 && progress < 100 && '正在优化代码...'}
            {progress === 100 && '生成完成！'}
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default UploadPage;